package com.zhm.demo.security;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    public Map<String, UserDetails> users() {
        // 构建用户"user"，角色ROLE_USER
        LoginUser user = new LoginUser();
        user.setUsername("zhm");
        user.setPassword("$2a$10$Io7bVU9laqpZre0t.6HkxO0aZlBj08dxvJxcEXf3kT2pCkp4LyIhO");
        user.setAuthorities(List.of(new SimpleGrantedAuthority("ROLE_USER")));  // 角色需加ROLE_前缀

        // 构建管理员"admin"，角色ROLE_USER和ROLE_ADMIN
        LoginUser admin = new LoginUser();
        admin.setUsername("admin");
        admin.setPassword("$2a$10$Io7bVU9laqpZre0t.6HkxO0aZlBj08dxvJxcEXf3kT2pCkp4LyIhO");
        admin.setAuthorities(List.of(
            new SimpleGrantedAuthority("ROLE_USER"),
            new SimpleGrantedAuthority("ROLE_ADMIN")  // 多角色配置
        ));

        return Map.of(user.getUsername(), user, admin.getUsername(), admin);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return users().get(username);
    }
}
